using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using WinformDevFramework.Services;

namespace WinformDevFramework
{
    public partial class Frmw_BuyInWarehouse : BaseForm1
    {
        private Iw_BuyInWarehouseServices _w_BuyInWarehouseServices;
        private Iw_BuyServices _wBuyServices;
        private Iw_BuyDetailServices _w_BuyDetailServices;
        private Iw_Warehouseervices _w_Warehouseervices;
        private Iw_BuyInWarehouseDetailServices _wBuyInWarehouseDetailServices;
        private Iw_PaymentDetailServices _w_PaymentDetailServices;
        public Frmw_BuyInWarehouse(Iw_BuyInWarehouseServices w_BuyInWarehouseServices, Iw_BuyServices wBuyServices, Iw_BuyDetailServices w_BuyDetailServices, Iw_Warehouseervices w_Warehouseervices, Iw_BuyInWarehouseDetailServices wBuyInWarehouseDetailServices, Iw_PaymentDetailServices w_PaymentDetailServices)
        {
            _w_BuyInWarehouseServices = w_BuyInWarehouseServices;
            InitializeComponent();
            _wBuyServices = wBuyServices;
            _w_BuyDetailServices = w_BuyDetailServices;
            _w_Warehouseervices = w_Warehouseervices;
            _wBuyInWarehouseDetailServices = wBuyInWarehouseDetailServices;
            _w_PaymentDetailServices = w_PaymentDetailServices;
        }

        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();

            // 设置隐藏列
            this.dataGridViewList.Columns["BuyInWarehouseCode"].HeaderText = "入库单号";
            this.dataGridViewList.Columns["BuyCode"].Visible = false;
            this.dataGridViewList.Columns["SupplierCode"].Visible = false;
            this.dataGridViewList.Columns["SupplierName"].HeaderText = "供应商名称";
            this.dataGridViewList.Columns["InvoicesDate"].HeaderText = "单据日期";
            this.dataGridViewList.Columns["InvoicesImage"].Visible = false;
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";
            this.dataGridViewList.Columns["Status"].Visible = false;

            //设置明细表 不可新增
            //dataGridViewDetail.AllowUserToAddRows=false;
            //设置明细 仓库
            Warehouse.DataSource=_w_Warehouseervices.Query();
            Warehouse.DisplayMember = "WarehouseName";
            Warehouse.ValueMember = "WarehouseCode";
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_BuyInWarehouse;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();           
            this.BuyCode.Text = model.BuyCode;  
            this.SupplierCode.Text = model.SupplierCode;  
            this.SupplierName.Text = model.SupplierName;  
            this.InvoicesDate.Text = model.InvoicesDate.ToString();  
            this.BuyInWarehouseCode.Text = model.BuyInWarehouseCode;  
            this.InvoicesImage.Text = model.InvoicesImage;  
            this.Remark.Text = model.Remark;  
            this.Status.Text = model.Status;
            SetDataToDetail(GetDetailData(model.BuyInWarehouseCode));
            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            SupplierCode.ReadOnly = true;
            SupplierName.ReadOnly=true;
            SetDataGridViewReadonlyStatus();
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            if (CheckData(BuyCode.Text))
            {
                base.EditFunction(sender, e);
                SetToolButtonStatus(formStatus);
                SupplierCode.ReadOnly = true;
                SupplierName.ReadOnly = true;
                BuyCode.ReadOnly = true;
                SetDataGridViewReadonlyStatus();
            }
               
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    w_BuyInWarehouse model = new w_BuyInWarehouse();
                    // TODO获取界面的数据
                    model.BuyCode=this.BuyCode.Text;
                    model.SupplierCode=this.SupplierCode.Text;
                    model.SupplierName=this.SupplierName.Text;
                    model.InvoicesDate=this.InvoicesDate.Value;
                    if (string.IsNullOrEmpty(this.BuyInWarehouseCode.Text))
                    {
                        model.BuyInWarehouseCode = $"CGRK{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                    }
                    else
                    {
                        model.BuyInWarehouseCode = this.BuyInWarehouseCode.Text;
                    }
                    model.InvoicesImage=this.InvoicesImage.Tag?.ToString();
                    model.Remark=this.Remark.Text;
                    model.Status="01";

                    if (_w_BuyInWarehouseServices.Exists(p => p.BuyInWarehouseCode.Equals(model.BuyInWarehouseCode)))
                    {
                        MessageBox.Show("入库单号已存在！请稍后在保存！", "提示");
                        return;
                    }
                    #region 明细表

                    List<w_BuyInWarehouseDetail> dataDetails = new List<w_BuyInWarehouseDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_BuyInWarehouseDetail detail = new w_BuyInWarehouseDetail();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                            detail.WarehouseCode = row.Cells["Warehouse"].Value.ToString();
                            detail.WarehouseName= row.Cells["Warehouse"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsCode"].FormattedValue.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.BuyCode = row.Cells["BuyCodeD"].FormattedValue.ToString();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            dataDetails.Add(detail);
                        }
                    }

                    #endregion
                    int id = _w_BuyInWarehouseServices.AddBuyInWarehouseInfo(model, dataDetails);
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                        txtID.Text = id.ToString();
                        BuyInWarehouseCode.Text = model.BuyInWarehouseCode;
                        SetDataToDetail(GetDetailData(model.BuyInWarehouseCode));
                    }
                }
                // 修改
                else
                {
                    w_BuyInWarehouse model = _w_BuyInWarehouseServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.BuyCode=this.BuyCode.Text;
                    model.SupplierCode=this.SupplierCode.Text;
                    model.SupplierName=this.SupplierName.Text;
                    model.InvoicesDate=this.InvoicesDate.Value;
                    model.BuyInWarehouseCode=this.BuyInWarehouseCode.Text;
                    model.InvoicesImage=this.InvoicesImage.Tag?.ToString();
                    model.Remark=this.Remark.Text;
                    model.Status=this.Status.Text;
                    #region 明细表

                    List<w_BuyInWarehouseDetail> dataDetails = new List<w_BuyInWarehouseDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_BuyInWarehouseDetail detail = new w_BuyInWarehouseDetail();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsCode"].FormattedValue.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.BuyCode = row.Cells["BuyCodeD"].FormattedValue.ToString();
                            detail.WarehouseCode = row.Cells["Warehouse"].Value.ToString();
                            detail.WarehouseName = row.Cells["Warehouse"].FormattedValue.ToString(); 
                            detail.BuyInWarehouseCode =  row.Cells["BuyInWarehouseCodeD"].FormattedValue.ToString();
                            detail.BuyInWarehouseDetailCode = row.Cells["BuyInWarehouseDetailCode"].FormattedValue.ToString();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            dataDetails.Add(detail);
                        }
                    }

                    #endregion
                    if (_w_BuyInWarehouseServices.UpdateBuyInWarehouseInfo(model, dataDetails))
                    {
                        MessageBox.Show("保存成功！", "提示");
                        SetDataToDetail(GetDetailData(model.BuyInWarehouseCode));
                    }
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled= !isAdd;
            SetDataToDetail(GetDetailData(BuyInWarehouseCode.Text));
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            if (CheckData(BuyCode.Text))
            {
                base.DelFunction(sender, e);
                var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    if (_w_BuyInWarehouseServices.DeleteBuyInWarehouseInfo(new w_BuyInWarehouse()
                        {
                            ID = txtID.Text.ToInt32(),
                            BuyInWarehouseCode = BuyInWarehouseCode.Text
                        }))
                    {
                        formStatus = FormStatus.Del;
                        SetToolButtonStatus(formStatus);
                        //列表重新赋值
                        dataGridViewDetail.Rows.Clear();
                        this.dataGridViewList.DataSource = GetData();
                        dataGridViewDetail.Rows.Clear();
                        InvoicesImage.Tag = string.Empty;
                        //InvoicesImage. = null;
                    }

                }
            }
            
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }
        }

        public override bool ValidateData()
        {
            if (string.IsNullOrEmpty(BuyCode.Text))
            {
                MessageBox.Show("采购订单不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(SupplierCode.Text))
            {
                MessageBox.Show("供应商编号不能为空！");
                return false;
            }
            if (string.IsNullOrEmpty(SupplierName.Text))
            {
                MessageBox.Show("供应商名称不能为空！");
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<w_BuyInWarehouse> GetData()
        {
            List<w_BuyInWarehouse> data = new List<w_BuyInWarehouse>();
            data = _w_BuyInWarehouseServices.Query();
            return data;
        }

        private void BuyCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!string.IsNullOrEmpty(BuyCode.Text.Trim()))
                {
                    var data = _wBuyServices.QueryByClause(p => p.BuyCode.Equals(BuyCode.Text.Trim()));
                    if (data != null)
                    {
                        SupplierName.Text = data.SupplierName;
                        SupplierCode.Text = data.SupplierCode;
                        //明细带出数据

                        List<w_BuyDetail> buyDetails = new List<w_BuyDetail>();
                        buyDetails = _w_BuyDetailServices.QueryListByClause(p => p.BuyCode == data.BuyCode);
                        SetDataToDetail(buyDetails);
                    }
                    else
                    {
                        MessageBox.Show("采购单号不存在！");
                    }
                }
            }
        }
        /// <summary>
        /// 明细表 设置数据 --采购单号带出
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_BuyDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["BuyCodeD"].Value = p.BuyCode;
                row.Cells["GoodsName"].Value = p.GoodsName;
                row.Cells["GoodsCode"].Value = p.GoodsCode;
                row.Cells["Warehouse"].Value = "CK001";
                row.Cells["GoodsSpec"].Value = p.GoodsSpec;
                row.Cells["GoodsUnit"].Value = p.GoodsUnit;
                row.Cells["Number"].Value = 0;
                row.Cells["RemarkD"].Value = p.Remark;

                //row.Cells["BuyID"].Value = p.BuyID;
                //row.Cells["BuyCodeD"].Value = p.BuyCode;
                //row.Cells["BuyDetailCode"].Value = p.BuyDetailCode;
            });
        }
        /// <summary>
        /// 明细表 设置数据 --主表带出
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_BuyInWarehouseDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["BuyCodeD"].Value = p.BuyCode;
                row.Cells["GoodsName"].Value = p.GoodsName;
                row.Cells["GoodsCode"].Value = p.GoodsCode;
                row.Cells["GoodsSpec"].Value = p.GoodsSpec;
                row.Cells["GoodsUnit"].Value = p.GoodsUnit;
                row.Cells["Number"].Value = p.Number;
                row.Cells["RemarkD"].Value = p.Remark;
                row.Cells["Warehouse"].Value = p.WarehouseCode;
                row.Cells["BuyInWarehouseCodeD"].Value = p.BuyInWarehouseCode;
                row.Cells["BuyInWarehouseDetailCode"].Value = p.BuyInWarehouseDetailCode;
            });
        }
        /// <summary>
        /// 获取明细数据
        /// </summary>
        /// <returns></returns>
        private List<w_BuyInWarehouseDetail> GetDetailData(string code)
        {
            List<w_BuyInWarehouseDetail> data = new List<w_BuyInWarehouseDetail>();
            data = _wBuyInWarehouseDetailServices.QueryListByClause(p => p.BuyInWarehouseCode == code);
            return data;
        }
        /// <summary>
        /// 数据校验
        /// </summary>
        /// <returns></returns>
        private bool CheckData(string code)
        {
            //是否已收款
            //if (_w_PaymentDetailServices.Exists(p => p.BuyCode == code))
            //{
            //    MessageBox.Show("该采购单已付款，不能操作！", "提示");
            //    return false;
            //}
            return true;
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }
        private void SetDataGridViewReadonlyStatus()
        {
            dataGridViewDetail.ReadOnly = false;
            string[] cols = { "Number", "Warehouse", "RemarkD" };
            foreach (DataGridViewColumn column in dataGridViewDetail.Columns)
            {
                if (!cols.Contains(column.Name))
                {
                    column.ReadOnly = true;
                }
            }
        }
    }
}
